package com.pan.crawler.old;

import com.pan.entity.Chapter;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;

import java.time.Duration;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Page {

    private EdgeDriver edgeDriver;

    public Page(){
        edgeDriver = new EdgeDriver();
//        edgeDriver.manage().window().minimize();
    }

    public String get(Chapter chapter)  {
        String url = chapter.getUrl();
        WebElement contentDiv = null;
        for (int i = 0; i < 5; i++) {
            try {
                edgeDriver.navigate().to(url);
                edgeDriver.findElement(By.className("footer"));
                edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(4));
                contentDiv = edgeDriver.findElement(By.id("content"));
                break;
            }catch (Exception e){
                if (i==4){
                    throw new RuntimeException("这个页面出不来");
                }
                try {
                    int r = new Random().nextInt(3000);
                    Thread.sleep(r);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
                continue;
            }
        }
        String content = contentDiv.getText();
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        String delStr = contentDiv.findElement(By.id("center_tip")).getText();
        String delRegex = "["+delStr+"]";
        Pattern pattern = Pattern.compile(delRegex);
        Matcher matcher = pattern.matcher(content);
        content = matcher.replaceAll("");
        String title = chapter.getTitle();
        content = "\n\n\n\n\n\n\n\n"+title+"\n\n\n\n"+content;
        return content;
    }

    public void close(){
        edgeDriver.quit();
    }
}
